import os
import email
import enronConfig
import errorStrings, debugTrace
import siteConfig

class mailDirReader:
	
	dataDir				= None
	errorStringsInst	= None
	debugTraceInst		= None

	def __init__(self, dataDir):
		self.dataDir			= dataDir
		self.errorStringsInst	= errorStrings.errorStrings()
		self.debugTraceInst		= debugTrace.debugTrace(siteConfig.debugEnabled)
	
	def getUsers(self):
		return os.listdir(self.dataDir)

	def listMailbox(self, user):
		return self.getDirList(os.path.join(self.dataDir, user))
	
	def fetchMails(self, user, mailBox = []):
		mailDirs	= mailBox
		mailList	= []

		if len(mailDirs) == 0:
			mailDirs	= self.listMailbox(user)

		for dir in mailDirs:
			fileList	 = os.listdir(dir)
			for file in fileList:
				fileName	= os.path.join(dir, file)
				if os.path.isfile(fileName):
					fh = open(fileName, 'r')
					mailList.append(email.message_from_file(fh))
					fh.close()

		return mailList
		
	def getDirList(self, dir):
		
		dirList	= os.listdir(dir)
		deepDirList	= []
		
		for aDir in dirList:
			dirName	= os.path.join(dir, aDir)
			if os.path.isfile(dirName) is False:
				deepDirList.append(dirName)
				localList	= self.getDirList(os.path.join(dir, aDir))
				for item in localList:
					deepDirList.append(item)

		return deepDirList

if __name__ == "__main__":
	inst	= mailDirReader(enronConfig.enronMailDir)
	print inst.listMailbox('naresh')
	#print inst.getUsers()
	
	#print inst.fetchMails('hyvl-d', inst.listMailbox('hyvl-d'))
